Textview 第一次点击时为空,但第二次点击时更新

2024-05-22

它是使用兼容性包的小型 Android 2.2 测试应用程序。我正在尝试更新列表项选择上另一个活动的另一个片段上的文本视图。但问题是,每次第一次单击都会返回空指针异常,并且只有在第二次尝试时,其文本才会更改。我想知道为什么会发生这种情况以及什么是好的解决方案。

列表活动:-

public class ListActivity extends FragmentActivity implements
    ListFragment.OnItemSelectedListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list);
    }

    @Override
    public void onItemSelected(int index) {
        // TODO Auto-generated method stub

        // Check to see if there is a frame in which to embed the
        // detail fragment directly in the containing UI.
        View detailsFrame = findViewById(R.id.detailcontainer);
        if (detailsFrame != null
                && detailsFrame.getVisibility() == View.VISIBLE) {

            DetailFragment detailFragment = (DetailFragment)    getSupportFragmentManager()
                    .findFragmentById(R.id.detailcontainer);

            if (detailFragment == null) {

                detailFragment = new DetailFragment();
            }

            // Execute a transaction, replacing any existing fragment
            // with this one inside the frame.

            getSupportFragmentManager().beginTransaction()
                    .replace(R.id.detailcontainer, detailFragment).commit();

            detailFragment.setTextView(index);

        } else {

            // Otherwise we need to launch a new activity to display
            Intent intent = new Intent(this, DetailActivity.class);
            intent.putExtra("index", index);
            startActivity(intent);

        }
    }
}

列表片段:-

public class ListFragment extends Fragment {

    private OnItemSelectedListener listener;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        String[] countries = new String[] { "India", "Pakistan", "Sri Lanka",
                "China", "Bangladesh", "Nepal", "Afghanistan", "North Korea",
                "South Korea", "Japan" };

        View view = inflater.inflate(R.layout.list_fragment, container, false);

        ListView listView = (ListView) view.findViewById(R.id.listView);

        // Populate list
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(
                this.getActivity(), android.R.layout.simple_list_item_1,
                countries);
        listView.setAdapter(adapter);

        // operation to do when an item is clicked
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                Toast.makeText(getActivity(), "ListItem Number " + position,
                        Toast.LENGTH_SHORT).show();


                listener.onItemSelected(position);
            }
        });

        return view;
    }

    // Container Activity must implement this interface
    public interface OnItemSelectedListener {
        public void onItemSelected(int index);
    }

    // To ensure that the host activity implements this interface
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        if (activity instanceof OnItemSelectedListener) {
            listener = (OnItemSelectedListener) activity;
        } else {
            throw new ClassCastException(activity.toString()
                    + " must implemenet ListFragment.OnItemSelectedListener");
        }
    }

    public void operation(int index) {

        listener.onItemSelected(index);
    }

}

详细活动:-

public class DetailActivity extends FragmentActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        DetailFragment details;
        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {

            finish();
            return;
        }

        if (savedInstanceState == null) {
            // During initial setup, plug in the details fragment.
            details = new DetailFragment();
            details.setArguments(getIntent().getExtras());
            getSupportFragmentManager().beginTransaction()
                    .add(android.R.id.content, details).commit();
        }

        Bundle extras = getIntent().getExtras();
        int index = extras.getInt("index");
        try {
            details = (DetailFragment) getSupportFragmentManager()
                    .findFragmentById(R.id.detailfragment);
            details.setTextView(index);

        } catch (NullPointerException ex) {
            ex.getStackTrace();
        }

    }

}

详细片段:-

public class DetailFragment extends Fragment {

    String[] capitals;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        if (container == null)
            return null;

        capitals = new String[] { "delhi", "karachi", "colombo", "beijing",
                "dhaka", "katmandu", "Afghanistan", "pyongyang", "seoul",
                "tokyo" };

        View v = inflater.inflate(R.layout.detail_fragment, container, false);

        return v;
    }

    public void setTextView(int index) {

        try {
            TextView view = (TextView) getView().findViewById(R.id.detailView);
            view.setText(capitals[index]);

        } catch (NullPointerException ex) {
            ex.getStackTrace();
        }
    }

    public int getShownIndex() {
        return getArguments().getInt("index", 0);
    }
}

更新:- 我正在添加详细信息片段 xml:-

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:background="@color/lightblue"
android:orientation="vertical" >

<TextView
    android:id="@+id/detailView"
    android:layout_width="100dp"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:text="@string/detail_frag" />

</RelativeLayout>

不要在 DetailActivity 中执行details.setTextView(index),而是在 DetailFragment 的 onActivityCreated 中设置 TextView 的值,同时传递要在 Detailactivity 中的片段 setArgument 方法中设置的值...

  DetailsFragment details = new DetailsFragment();
  details.setArguments(getIntent().getExtras());  // pass the value of text view here

在片段 onActivityCreated 中通过 getArguments() 获取该值并将其设置在 textview 中。

编辑发送选择加载片段的值

列表中的活动

  detailFragment = getFragmentbyTag
  if(detailFragment == null)
      Create Fragment and Add it and Set Arguments here as well
  else
      detailFragment.setTextView(value); // fragment already loaded no need to set arguments

如果您想每次替换而不是添加一次并使用添加/加载的片段,请每次使用 setarguments.... 并删除以前的片段并添加新片段(带参数)但是添加一次并重用是首选,而不是删除和每次点击时添加/替换

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Textview 第一次点击时为空,但第二次点击时更新 的相关文章

随机推荐

  • Immutable.js 推入嵌套对象中的数组

    假设有一个对象 const object foo bar 1 2 3 我需要推动4 to object foo bar array 现在我正在这样做 const initialState Immutable fromJS object co
  • 更改 WireMock __files 目录

    来自docs http wiremock org docs stubbing 要从文件中读取正文内容 请将文件放在 files 下 目录 默认情况下 这应该位于 src test resources 下 从 JUnit 规则运行时 当独立运
  • 夏季化上方的树枝和行

    我对 twig 有点陌生 我知道可以在模板中添加值并将它们收集在变量中 但我真正需要的是在总结它们之前在模板中显示汇总值 我需要像旧 symfony 中的插槽之类的东西 或者在 php 中我可以通过 ob start 来做到这一点 以某种方
  • Golang 中的确定性 RSA 加密 - 如何在多次加密下为给定消息获得相同的结果

    对于下面的RSA加密代码 每次对同一条消息进行加密时 结果都会不同 我发现这是由于rand Reader in the rsa EncryptOAEP功能使其更加安全doc https pkg go dev crypto rsa Encry
  • 身份未映射异常

    System Security Principal IdentityNotMappedException 无法转换部分或全部身份引用 该错误仅在应用程序注册后出现一次 当 SecurityIdentifier 无法映射时 例如 返回 Ide
  • 无法为对象堆保留足够的空间

    每次尝试运行该程序时 我都会重复出现以下异常 VM初始化期间发生错误 无法为对象堆保留足够的空间 无法创建Java虚拟机 我尝试增加虚拟内存 页面大小 和 RAM 大小 但无济于事 我怎样才能消除这个错误 运行 JVM XX MaxHeap
  • 在多个 emacs 缓冲区上执行特定命令

    有没有办法在多个缓冲区上执行 emacs 命令 而不必单独选择它们并在每个单独的缓冲区上执行它 我通常打开与特定正则表达式匹配的多个文件 例如 py并希望启用特定模式 例如hs minor mode or glasses mode在每个上
  • 过滤列表视图并获取正确的 onclick 项目

    我有一个列表视图 并且已经实现了过滤 假设我有项目 A B 和 C 如果我在过滤框中输入 B 则只会显示项目 B 它是列表的位置 0 之前位于位置 1 因此 当我调用 onClick 项目时 我得到 id position 0 这导致显示有
  • 字节到二进制字符串 C# - 显示所有 8 位数字

    我想在文本框中显示一个字节 现在我正在使用 Convert ToString MyVeryOwnByte 2 但是 当字节开头有 0 时 这些 0 就会被删除 例子 MyVeryOwnByte 00001110 Texbox shows g
  • React Context - Context.Consumer 与 Class.contextType

    我正在学习新引入的 React Context API 但我注意到它在示例中的消耗存在一些不一致 有的还是用原来的上下文 消费者HOC 方法 而有些 包括 React 文档 使用静态类 contextType method 有什么区别以及为
  • __FUNCTION__ 宏的 C# 版本

    有人对 C FUNCTION 宏的 C 版本有好的解决方案吗 编译器似乎不喜欢它 尝试使用这个代替 System Reflection MethodBase GetCurrentMethod Name C 没有 LINE or FUNCTI
  • 对数字进行向上和向下舍入 C++

    我试图让我的程序分别向上和向下舍入数字 例如 如果数字是3 6 我的程序应该四舍五入最接近的数字 4 如果该数字是3 4 它将向下舍入为 3 我尝试使用ceil库获取 3 个项目的平均值 results ceil marks1 marks2
  • Flask 应用程序中的双 IPv4 和 IPv6 支持

    是否可以运行 Flask 来监听 IPv4 和 IPv6 即双 IP 堆栈 据我检查 可以使用以下命令在 IPv4 中运行 app run host 0 0 0 0 port port debug True 或 IPv6 使用 app ru
  • 最新的 Windows 10 更新后 R 将无法运行

    我已经更新了我的 Windows 但 R 无法运行 因此 R studio 也无法运行 当我运行 R GUI 时 它只是冻结并且没有响应 我已允许防火墙豁免铬 我正在使用 Windows Insider 计划并且刚刚更新到 Windows
  • 从 XPath 中的选择中排除特定标记

    我知道这是一个简单的问题 但我无法弄清楚 考虑以下简单的 XML 文档
  • PHP Web 应用程序 (Magento) 遭到黑客攻击;这段黑客代码有什么作用?

    我刚刚安装的 Magento 1 3 2 4 被黑了 你能告诉我这段代码的目的是什么吗 另外 如何阻止这种情况以及如何发现漏洞 谢谢 function net match network ip ip arr explode network
  • 如何在 Vue.js 2 中使用事件总线通过自定义事件传递数据

    我在用着Vue js 2 5 x 在我的玩具项目中 我实现了一个事件总线 类似于所示的here https alligator io vuejs global event bus 事件总线在 Vue 原型中全局注册为 eventBus 然后
  • 阅读 Stack Overflow RSS 源

    我正在尝试获取未回答问题的列表the feed https stackoverflow com feeds 但我在阅读时遇到困难 const string RECENT QUESTIONS https stackoverflow com f
  • 抽屉式导航不显示片段

    我创建了一个新的 Android Studio 项目 我的 MainActivity 是导航抽屉活动 所以 我无法显示碎片 我在互联网上和这里读过很多帖子 解释 我打开导航抽屉 选择菜单 播客 PodcastsFragment 应该显示 但
  • Textview 第一次点击时为空,但第二次点击时更新

    它是使用兼容性包的小型 Android 2 2 测试应用程序 我正在尝试更新列表项选择上另一个活动的另一个片段上的文本视图 但问题是 每次第一次单击都会返回空指针异常 并且只有在第二次尝试时 其文本才会更改 我想知道为什么会发生这种情况以及