我跟着这个家伙tutorial关于如何制作一个ActionBar。假设我想在其中一个片段中更改TextView。所以我在onCreate:
下的StartActivity.java中添加了这个TextView textview = (TextView) findViewById(R.id.textView1);
textview.setText("HI!");
当我启动应用程序时,它会崩溃。有人能指出我正确的方向吗?
我希望有人花时间看这个家伙的教程,因为他的布局与我的基本相同。谢谢。
答案 0 :(得分:8)
如果你想改变你的组件,我建议你在片段中创建一个方法,如下所示:
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class DetailFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.details, container, false);
return view;
}
public void setText(String text){
TextView textView = (TextView) getView().findViewById(R.id.detailsText);
textView.setText(text);
}
}
答案 1 :(得分:4)
你能尝试用getActivity()替换getView()吗?
public void setText(String text){
TextView textView = (TextView) getActivity().findViewById(R.id.detailsText);
textView.setText(text);
}
答案 2 :(得分:1)
我找到了答案here,并在Stack overflow
上找到了答案它使用了inflater :(对我来说,它有效)
public class MyFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View inf = inflater.inflate(R.layout.fragment_place, container, false);
TextView tv = (TextView) inf.findViewById(R.id.textview);
tv.setText("New text");
return inf;
}
}
答案 3 :(得分:0)
在您的主要活动中,像这样实例化片段类
public class MainActivity extends AppCompatActivity {
private YourFragmentClass your_fragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
your_fragment = new YourFragmentClass("pass the string value here")
}
}
在片段类中,您可以像这样获取字符串和setText
public class YourFragmentclass extends Fragment {
private String your_text;
public YourFragmentClass(String your_text) {
this.your_text = your_text;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = (View)inflater.inflate(R.layout.fragment_layout, container, false);
//set the text of your text view
TextView textView = (TextView) view.findViewById(R.id.text_view_id);
textView.setText(your_text);
}
}