这是我的片段代码,当它不起作用时没有错误放置! 每个片段都有语音识别按钮,inputText接收文本,给定文本与inputText进行比较,如果不匹配则突出显示为红色,
public class LayoutOne extends Fragment {
protected static final int RESULT_SPEECH = 1;
private ImageButton btnSpeak;
private TextView inputText;
private TextView givenText;
public static Fragment newInstance(Context context) {
LayoutOne f = new LayoutOne();
return f;
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.layout_one);
inputText = (TextView)getView().findViewById(R.id.inputText);
givenText = (TextView)getView().findViewById(R.id.givenText);
btnSpeak = (ImageButton)getView().findViewById(R.id.btnSpeak);
btnSpeak.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, "en-US");
try{
startActivityForResult(intent, RESULT_SPEECH);
inputText.setText("");
}catch(ActivityNotFoundException a) {
}
}
});
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
ViewGroup v = (ViewGroup) inflater.inflate(R.layout.layout_one, null);
return v;
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case RESULT_SPEECH: {
if (resultCode == -1 && null != data) {
ArrayList<String> text = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
inputText.setText(text.get(0));
if(givenText.getText().toString().equalsIgnoreCase(inputText.getText().toString())){
inputText.setBackgroundColor(Color.parseColor("BLUE"));
}
else{
{inputText.setBackgroundColor(Color.parseColor("RED"));}
}
}
break;
}
}
}
}
任何想法?
答案 0 :(得分:0)
首先你需要以不同的方式创建你的片段类,因为你没有inflater,片段没有使用泛型onCreate作为其他android类......
Public class myFragment extends Fragment{
TextView testTextView;
View myFragmentView
public View onCreateView(LayoutInflater viewInflation, ViewGroup container,
Bundle SavedInstantState) {
myFragmentView = viewInflation.inflate(
R.layout.myfragment_layout, container, false);
testTextView = myFragmentView.findViewById(R.id.testTextView);
}
}
这是如何设置片段的基本示例....然后,您可以使用事务管理器在FragmentActivity
中对其进行充气,并创建Fragment类的字段。< / p>
<强> [更新] 强>
另外,如果您使用eclipse的可视化编辑器,您只需从可视菜单中拖放一个片段,它应该只询问您想要附加到哪个片段类。