将 int 可绘制资源设置为 onClick
Posted
技术标签:
【中文标题】将 int 可绘制资源设置为 onClick【英文标题】:setting int drawable resource to onClick 【发布时间】:2018-05-03 00:22:32 【问题描述】:我目前正在开发一个包含 10 个问题的测验应用程序,我需要在选定的问题字段中显示 5 张图像,并在单击文本时发出警报对话框作为提示。 我已设置可绘制资源文件以将每个单独的图像显示为引用的文本。单击时如何将资源drawable int正确设置为文本? 现在,我遇到了一个错误。
QuestionLibrary.java
// This file contains questions from QuestionBank
class QuestionLibrary
// array of questions
private String mQuestions [] =
"Question1",
"Question2",
"Question3",
"Question4?",
"Qustion5",
"Question6",
"Question7",
"Question8",
"Question9",
"Question10"
;
// array of multiple choices for each question
private String mChoices [][] =
// choices goes here
;
//setting images
public static int[] image_drawables = new int[]
R.drawable_01, R.drawable_02, R.drawable_03, R.drawable_04
;
// array of correct answers - in the same order as array of questions
private String mCorrectAnswers[] =
Answers goes here
;
// text to show hint reference
private static String[] click_me_text =
"", "", "Hint", "", "Hint", "", "", "Click me!", "Click me!", "", "",
;
// method returns click_me text from array textQuestions[] based on array index
String getTextHint(int a)
return click_me_text[a];
// method returns number of questions
int getLength()
return mQuestions.length;
// method returns question from array textQuestions[] based on array index
String getQuestion(int a)
return mQuestions[a];
// method return a single multiple choice item for question based on array index,
// based on number of multiple choice item in the list - 1, 2, 3 or 4 as an argument
String getChoice(int index, int num)
return mChoices[index][num-1];
// method returns correct answer for the question based on array index
String getCorrectAnswer(int a)
return mCorrectAnswers[a];
MainActivity.java
public class MainActivity extends AppCompatActivity
private QuestionLibrary mQuestionLibrary = new QuestionLibrary();
//initializing buttons
Button button1;
Button button2;
Button button3;
Button button4;
TextView msingleQuestion;
TextView mQuestion; //current question to answer
TextView mClickMe; // text to be clicked which should display image
private int mQuestionNumber = 0; // current question number
private String mAnswer; // correct answer for question in mQuestionView
private int mquizNumber = 1;
private int mfailedQuestions = 5;
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_begineer);
// set textViews here
msingleQuestion = (TextView) findViewById(R.id.singleQuestion);
mQuestion = (TextView) findViewById(R.id.txtQuestion);
mClickMe = (TextView) findViewById(R.id.click_me);
button1 = (Button) findViewById(R.id.firstOption);
button2 = (Button) findViewById(R.id.secondOption);
button3 = (Button) findViewById(R.id.thirdOption);
button4 = (Button) findViewById(R.id.fourthOption);
updateQuestion(); //update question
// setting respective animations for the buttons
blinkClickMe();
private void blinkClickMe()
Animation anim = new AlphaAnimation(0.0f, 1.0f);
anim.setDuration(60);
anim.setStartOffset(30);
anim.setRepeatMode(Animation.REVERSE);
anim.setRepeatCount(Animation.INFINITE);
mClickMe.startAnimation(anim);
private void updateQuizNumber(int mquizNumber)
msingleQuestion.setText("" + mquizNumber+"/"+mQuestionLibrary.getLength());
private void updateQuestion()
// check if we are not outside array bounds for questions
if(mQuestionNumber<mQuestionLibrary.getLength() )
// set text for hint and click_me
mClickMe.setText(mQuestionLibrary.getTextHint(mQuestionNumber));
// set the text for new question, and new 4 alternative to answer on four buttons
mQuestion.setText(mQuestionLibrary.getQuestion(mQuestionNumber));
button1.setText(mQuestionLibrary.getChoice(mQuestionNumber, 1));
button2.setText(mQuestionLibrary.getChoice(mQuestionNumber, 2));
button3.setText(mQuestionLibrary.getChoice(mQuestionNumber, 3));
button4.setText(mQuestionLibrary.getChoice(mQuestionNumber,4));
mAnswer = mQuestionLibrary.getCorrectAnswer(mQuestionNumber);
mQuestionNumber++;
else
Toast.makeText(BeginnerActivity.this, "It was the last question!", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(this, MenuOptions.class);
// intent.putExtra("score", mScore); // pass the current score to the second screen
startActivity(intent);
public void onClick(View view)
//all logic for all answers buttons in one method
final Button answer = (Button) view;
// if the answer is correct, increase the score
if (answer.getText().equals(mAnswer) )
answer.setBackgroundColor(Color.GREEN);
// blink correct answer
Animation anim = new AlphaAnimation(0.0f, 1.0f);
anim.setDuration(60);
anim.setStartOffset(30);
anim.setRepeatMode(Animation.REVERSE);
anim.setRepeatCount(Animation.RELATIVE_TO_PARENT);
answer.startAnimation(anim);
else
answer.setBackgroundColor(Color.RED);
mfailedQuestions--;
updateLives(mfailedQuestions);
if (mQuestionNumber < mQuestionLibrary.getLength())
// once user answer the question, we move on to the next one, if any
Handler handler = new Handler();
handler.postDelayed(new Runnable()
@Override
public void run()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN)
answer.setBackground(ContextCompat.getDrawable(getApplicationContext(), R.drawable.rounded_button_questions));
updateQuestion();
mquizNumber++;
updateQuizNumber(mquizNumber);
, 1000);
else
Handler handler = new Handler();
handler.postDelayed(new Runnable()
@Override
public void run()
Intent intent = new Intent(BeginnerActivity.this, MenuOptions.class);
// intent.putExtra("score", mScore); // pass the current score to the second screen
startActivity(intent);
, 1000);
public void revealImage(View view)
loadImage();
private void loadImage()
AlertDialog.Builder builder = new AlertDialog.Builder(this);
LayoutInflater inflater = this.getLayoutInflater();
// what is needed here?
View dialogView = inflater.inflate(QuestionLibrary.image_drawables[mQuestionNumber], null);
builder.setView(dialogView)
.create().show();
@Override
public void onFinish()
timer.setText("time's up!!");
Animation anim = new AlphaAnimation(0.0f, 1.0f);
anim.setDuration(60);
anim.setStartOffset(30);
anim.setRepeatMode(Animation.INFINITE);
anim.setRepeatCount(Animation.RELATIVE_TO_PARENT);
timer.startAnimation(anim);
Handler handler = new Handler();
handler.postDelayed(new Runnable()
@Override
public void run()
finish();
, 500);
错误致命异常:main 进程:com.example.benkeys.pianoquizgame,PID:3961 java.lang.IllegalStateException:无法执行方法 安卓:点击 在 android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293) 在 android.view.View.performClick(View.java:5637) 在 android.view.View$PerformClick.run(View.java:22429) 在 android.os.Handler.handleCallback(Handler.java:751) 在 android.os.Handler.dispatchMessage(Handler.java:95) 在 android.os.Looper.loop(Looper.java:154) 在 android.app.ActivityThread.main(ActivityThread.java:6119) 在 java.lang.reflect.Method.invoke(本机方法) 在 com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886) 在 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776) 引起:java.lang.reflect.InvocationTargetException 在 java.lang.reflect.Method.invoke(本机方法) 在 android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288) 在 android.view.View.performClick(View.java:5637) 在 android.view.View$PerformClick.run(View.java:22429) 在 android.os.Handler.handleCallback(Handler.java:751) 在 android.os.Handler.dispatchMessage(Handler.java:95) 在 android.os.Looper.loop(Looper.java:154) 在 android.app.ActivityThread.main(ActivityThread.java:6119) 在 java.lang.reflect.Method.invoke(本机方法) 在 com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886) 在 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776) 引起:android.content.res.Resources$NotFoundException:文件 res/drawable-xxhdpi-v4/beginner_04.png 来自 xml 类型布局资源 编号 #0x7f060056 在 android.content.res.ResourcesImpl.loadXmlResourceParser(ResourcesImpl.java:990) 在 android.content.res.Resources.loadXmlResourceParser(Resources.java:2103) 在 android.content.res.Resources.getLayout(Resources.java:1115) 在 android.view.LayoutInflater.inflate(LayoutInflater.java:424) 在 android.view.LayoutInflater.inflate(LayoutInflater.java:377) 在 com.example.benkeys.pianoquizgame.BeginnerActivity.loadImage(BeginnerActivity.java:244) 在 com.example.benkeys.pianoquizgame.BeginnerActivity.revealImage(BeginnerActivity.java:237) 在 java.lang.reflect.Method.invoke(本机方法) 在 android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288) 在 android.view.View.performClick(View.java:5637) 在 android.view.View$PerformClick.run(View.java:22429) 在 android.os.Handler.handleCallback(Handler.java:751) 在 android.os.Handler.dispatchMessage(Handler.java:95) 在 android.os.Looper.loop(Looper.java:154) 在 android.app.ActivityThread.main(ActivityThread.java:6119) 在 java.lang.reflect.Method.invoke(本机方法) 在 com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886) 在 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776) 引起:java.io.FileNotFoundException:损坏的 XML 二进制文件 在 android.content.res.AssetManager.openXmlAssetNative(Native Method)
【问题讨论】:
您到底需要什么?? 我需要在我的 textview 上设置 int drawable xml,以便在单击时在对话框中显示图像 为什么要在textview中添加图片,可以使用对话框中的图片视图来显示。 只需使用这些图像视图创建客户视图,并将它们设置在警报对话框或带有必要侦听器的对话框片段中 所以不需要使用布局充气器来充气布局? 【参考方案1】:您可以使用这种方法:
getResources().getDrawable(R.drawable.drawable)
在 res/Drawable 中设置您的可绘制对象,并通过上面的代码获取它并放入您的对话框中。
如果您有多个可绘制对象,请使用 switch() 方法,如下所示:
switch(answeredQuestion)
case 1:
//show considered dialog box
break;
case 2:
// show considered dialog box
break;
...
case 10:
//show considered dialog box
default
break;
【讨论】:
我实际上每张图片都有不止一个可绘制的 xml 所以不需要使用布局充气器来充气布局? Builder.serView()以上是关于将 int 可绘制资源设置为 onClick的主要内容,如果未能解决你的问题,请参考以下文章
将图像从 Android 上的可绘制资源保存到 sdcard
如何将渐变可绘制设置为 FloatingActionButton 上的 backgroundTint 属性
Android可绘制对象资源之shape和layer-list使用