gpt4 book ai didi

java - 从 Activity 中搜索 fragment ID

转载 作者:行者123 更新时间:2023-12-03 18:04:27 24 4
gpt4 key购买 nike

我已经在 Stack Overflow 中尝试了大多数解决方案,但仍然无法根据需要搜索 fragment ID。我正在尝试 setBackgroundResource到我在 onCreate 下的 Activity 中的图像按钮但是当我编译它时面对空引用对象。当我搜索我的 imagebutton 时,想知道如何从 Activity 中调用 fragment 中的 id id 并运行它,它总是返回空引用对象。

我试过了:

1) getView()
2) RootView()
3)

android.support.v4.app.Fragment liBrary = getSupportFragmentManager()
.findFragmentById(R.id.imgbtn1);
imgBtn1 = (ImageButton) Library.getActivity().findViewById(R.id.imgbtn1);
imgBtn1.setBackgroundResource(R.mipmap.exercise);

4)
Fragment liBrary = getSupportFragmentManager()
.findFragmentById(R.id.imgbtn1);
imgBtn1 = (ImageButton) Library.getActivity().findViewById(R.id.imgbtn1);
imgBtn1.setBackgroundResource(R.mipmap.exercise);

-编辑-
也只是为了更清楚地了解我如何设置我的 fragment :
MainActivity.java
  public class Homescreen extends AppCompatActivity implements TabLayout.OnTabSelectedListener {

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

android.app.Fragment library = getFragmentManager().findFragmentById(R.id.libraryMain);

(library.getView().findViewById(R.id.imgbtn1)).setBackgroundResource(R.mipmap.exercise);

}

fragment 类.java
public class Library extends Fragment {


@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState){
LinearLayout libraryLL = (LinearLayout) inflater.inflate(R.layout.library,
container, false);

希望这会有所帮助

最佳答案

在 xml 中创建 fragment 时,您会为 fragment 提供一个 ID,该 fragment 将充当硬币容器。

<fragment android:name="com.example.yourfragment"
android:id="@+id/test_fragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />

android.support.v4.app.Fragment Library = getSupportFragmentManager()
.findFragmentById(R.id.test_fragment);
imgbtn1 = (ImageButton) Library.getActivity().findViewById(R.id.imgbtn1);
imgbtn1.setBackgroundResource(R.mipmap.exercise);

关于java - 从 Activity 中搜索 fragment ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41343976/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com