如果没有文字怎么隐藏按钮?

时间:2017-05-06 13:15:39

标签: java android button

大家好我想隐藏按钮如果按钮文字为空,我怎么能这样做?例如,我有测验应用程序和一些问题没有4个答案,如果我有问题,3回答一个按钮总是显示没有文字。抱歉我的英语不好。

我的按钮代码就是这个......

public class ExamActivity extends Fragment  implements OnClickListener{
private static int levelNo=1;
private PlayQuizLevel level;
private int quextionIndex=0;
private boolean isSoundEffect;
private boolean isVibration;

private int NO_OF_QUESTION = 10;
private int totalScore=0;
private int score=0;
private int correctQuestion=0;
private int inCorrectQuestion=0;


private ImageView imgQuestion;
private Button btnOpt1, btnOpt2, btnOpt3, btnOpt4;
private TextView txtQuestionIndex, txtScore, txtLevel, txtQuestion;
private SharedPreferences settings;
boolean isSoundOn=false;
private Animation animation;
private MediaPlayer rightAnsware, wrongeAnsware;
private TextView txtTrueQuestion, txtFalseQuestion;
private final Handler mHandler = new Handler();
private SharedPreferences.Editor editor;
private View v;
Animation animationFromRight,animationFromLeft;
private InterstitialAd interstitial;
private List<PlayQuizQuestion> playQuizquestions =null;

private ProgressDialog progress;
String questionJson = "";
private ScrollView scrollView;
private Chronometer crono;

public interface Listener {
    public void displyHomeScreen();
    public GameData getGameData();
    public ExamCompletedActivity getQuizCompletedFragment();
}
Listener mListener = null;

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

    final int[] CLICKABLES = new int[] {
            R.id.btnOpt1, R.id.btnOpt2,
            R.id.btnOpt3,R.id.btnOpt4
    };
    for (int i : CLICKABLES) {
        v.findViewById(i).setOnClickListener(this);
    }

    settings = getActivity().getSharedPreferences(MenuHomeScreenActivity.PREFS_NAME, 0);

    resetAllValue();

    // Create an ad request. Check logcat output for the hashed device ID to get test ads on a physical device.
    // Create ad request.
    Resources ress = getResources();
    boolean isTestMode = ress.getBoolean(R.bool.istestmode);
    AdRequest adRequest =null;
    if(isTestMode){
        // Request for Ads
        System.out.println("Testing.... app");
        adRequest = new AdRequest.Builder()
                .addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
                .addTestDevice("B15149A4EC1ED23173A27B04134DD483")
                .addTestDevice("445AAA22783F2ED51E278767315DBDD5")
                .addTestDevice("A815D443EF9A92B3EF35A025747A4F16")
                .build();
    }else{
        System.out.println("Live Apps");
        adRequest = new AdRequest.Builder().build();
    }

    // Create the interstitial.
    interstitial = new InterstitialAd(getActivity());
    interstitial.setAdUnitId(getString(R.string.admob_intersitital));
    // Begin loading your interstitial.
    interstitial.loadAd(adRequest);

    return v;
}
public void setListener(Listener l) {
    mListener = l;
}

@Override
public void onStart() {
    super.onStart();
    updateUi();
}

@Override
public void onResume() {
    // TODO Auto-generated method stub
    super.onResume();
    updateUi();
}

void updateUi() {
    if (getActivity() == null) return;
    getActivity().findViewById(R.id.linearLayout1).setVisibility(View.GONE);
}

private void nextQuizQuestion(){
    scrollView.post(new Runnable() {
        @Override
        public void run() {
            scrollView.fullScroll(ScrollView.FOCUS_UP);
        }
    });

    int count_question_completed = mListener.getGameData().getCountHowManyQuestionCompleted();
    count_question_completed++;
    mListener.getGameData().setCountHowManyQuestionCompleted(count_question_completed);
    if(quextionIndex>=NO_OF_QUESTION){

        int howManyTimesPlayQuiz = mListener.getGameData().getCountHowManyTimePlay();
        System.out.println("How Many Time Play: "+howManyTimesPlayQuiz);
        howManyTimesPlayQuiz++;
        mListener.getGameData().setCountHowManyTimePlay(howManyTimesPlayQuiz);

        count_question_completed = mListener.getGameData().getCountHowManyQuestionCompleted();
        count_question_completed--;
        mListener.getGameData().setCountHowManyQuestionCompleted(count_question_completed);

        saveScore();

        displayInterstitial();

        getActivity().getSupportFragmentManager().popBackStack();
        getActivity().getSupportFragmentManager().beginTransaction().replace( R.id.fragment_container, mListener.getQuizCompletedFragment() ).addToBackStack( "tag" ).commit();


        blankAllValue();

        return;
    }

    btnOpt1.setClickable(true);
    btnOpt2.setClickable(true);
    btnOpt3.setClickable(true);
    btnOpt4.setClickable(true);

    btnOpt1.setTextColor(getResources().getColor(R.color.White));
    btnOpt2.setTextColor(getResources().getColor(R.color.White));
    btnOpt3.setTextColor(getResources().getColor(R.color.White));
    btnOpt4.setTextColor(getResources().getColor(R.color.White));

    if(quextionIndex-1<level.getNoOfQuestion()){
        int temp = quextionIndex;
        txtQuestionIndex.setText(""+ ++temp+"/"+NO_OF_QUESTION);
        String imgName = level.getQuestion().get(quextionIndex).getQuestion();
        Pattern p = Pattern.compile(" ");
        Matcher m = p.matcher(imgName);
        imgName = m.replaceAll("_");
        txtQuestion.setText(level.getQuestion().get(quextionIndex).getQuestion());

        ArrayList<String> options = new ArrayList<String>();
        options.addAll(level.getQuestion().get(quextionIndex).getOptions());
        Collections.shuffle(options);



        btnOpt1.setText(""+options.get(0).trim());
        btnOpt2.setText(""+options.get(1).trim());
        btnOpt3.setText(""+options.get(2).trim());
        btnOpt4.setText(""+options.get(3).trim());
        imgQuestion.setImageBitmap(level.getQuestion().get(quextionIndex).getQuestionBitmap());



    }if(quextionIndex==level.getNoOfQuestion()){
        System.out.println("only 1 quetion...");
    }

}
// Invoke displayInterstitial() when you are ready to display an interstitial.
public void displayInterstitial() {
    if (interstitial.isLoaded()) {
        interstitial.show();
    }
}


@Override
public void onClick(View v) {

    if(quextionIndex<level.getNoOfQuestion()){
        btnOpt1.setClickable(false);
        btnOpt2.setClickable(false);
        btnOpt3.setClickable(false);
        btnOpt4.setClickable(false);
        switch(v.getId()){
            case R.id.btnOpt1:

                if(btnOpt1.getText().toString().trim().equalsIgnoreCase(level.getQuestion().get(quextionIndex).getTrueAns().trim())){
                    quextionIndex++;

                    btnOpt1.setTextColor(getResources().getColor(R.color.White));
                    btnOpt2.setTextColor(getResources().getColor(R.color.White));
                    btnOpt3.setTextColor(getResources().getColor(R.color.White));
                    btnOpt4.setTextColor(getResources().getColor(R.color.White));
                    addScore();
                    btnOpt1.setBackgroundResource(R.drawable.button_green);
                    btnOpt1.startAnimation(animation);
                    btnOpt1.setTextColor(getResources().getColor(R.color.White));
                }else{
                    btnOpt1.setBackgroundResource(R.drawable.button_red);
                    btnOpt1.setTextColor(getResources().getColor(R.color.White));
                    btnOpt2.setTextColor(getResources().getColor(R.color.White));
                    btnOpt3.setTextColor(getResources().getColor(R.color.White));
                    btnOpt4.setTextColor(getResources().getColor(R.color.White));
                    wrongeQuestion();
                    quextionIndex++;
                }
                break;
            case R.id.btnOpt2:
                if(btnOpt2.getText().toString().trim().equalsIgnoreCase(level.getQuestion().get(quextionIndex).getTrueAns().trim())){
                    quextionIndex++;
                    btnOpt1.setTextColor(getResources().getColor(R.color.White));
                    btnOpt2.setTextColor(getResources().getColor(R.color.White));
                    btnOpt3.setTextColor(getResources().getColor(R.color.White));
                    btnOpt4.setTextColor(getResources().getColor(R.color.White));
                    addScore();
                    btnOpt2.setBackgroundResource(R.drawable.button_green);
                    btnOpt2.startAnimation(animation);
                    btnOpt2.setTextColor(getResources().getColor(R.color.White));
                }else{
                    btnOpt2.setBackgroundResource(R.drawable.button_red);
                    btnOpt2.setTextColor(getResources().getColor(R.color.White));
                    btnOpt1.setTextColor(getResources().getColor(R.color.White));
                    btnOpt3.setTextColor(getResources().getColor(R.color.White));
                    btnOpt4.setTextColor(getResources().getColor(R.color.White));
                    wrongeQuestion();
                    quextionIndex++;
                }
                break;
            case R.id.btnOpt3:
                if(btnOpt3.getText().toString().trim().equalsIgnoreCase(level.getQuestion().get(quextionIndex).getTrueAns().trim())){
                    quextionIndex++;
                    btnOpt1.setTextColor(getResources().getColor(R.color.White));
                    btnOpt2.setTextColor(getResources().getColor(R.color.White));
                    btnOpt3.setTextColor(getResources().getColor(R.color.White));
                    btnOpt4.setTextColor(getResources().getColor(R.color.White));
                    addScore();
                    btnOpt3.setBackgroundResource(R.drawable.button_green);
                    btnOpt3.startAnimation(animation);
                    btnOpt3.setTextColor(getResources().getColor(R.color.White));
                }else{
                    btnOpt3.setBackgroundResource(R.drawable.button_red);
                    btnOpt3.setTextColor(getResources().getColor(R.color.White));
                    btnOpt1.setTextColor(getResources().getColor(R.color.White));
                    btnOpt2.setTextColor(getResources().getColor(R.color.White));
                    btnOpt4.setTextColor(getResources().getColor(R.color.White));
                    wrongeQuestion();
                    quextionIndex++;
                }
                break;
            case R.id.btnOpt4:
                if(btnOpt4.getText().toString().trim().equalsIgnoreCase(level.getQuestion().get(quextionIndex).getTrueAns().trim())){
                    quextionIndex++;

                    btnOpt1.setTextColor(getResources().getColor(R.color.White));
                    btnOpt2.setTextColor(getResources().getColor(R.color.White));
                    btnOpt3.setTextColor(getResources().getColor(R.color.White));
                    btnOpt4.setTextColor(getResources().getColor(R.color.White));
                    addScore();
                    btnOpt4.setBackgroundResource(R.drawable.button_green);
                    btnOpt4.startAnimation(animation);
                    btnOpt4.setTextColor(getResources().getColor(R.color.White));
                }else{
                    btnOpt4.setBackgroundResource(R.drawable.button_red);
                    btnOpt4.setTextColor(getResources().getColor(R.color.White));
                    btnOpt1.setTextColor(getResources().getColor(R.color.White));
                    btnOpt2.setTextColor(getResources().getColor(R.color.White));
                    btnOpt3.setTextColor(getResources().getColor(R.color.White));
                    wrongeQuestion();
                    quextionIndex++;
                }
                break;
        }

    }else{
        mHandler.postDelayed(mUpdateUITimerTask, 2 * 10);
    }
    mHandler.postDelayed(mUpdateUITimerTask, 2 * 1000);
    txtScore.setText(""+totalScore);

}
private final Runnable mUpdateUITimerTask = new Runnable() {
    public void run() {
        btnOpt1.setBackgroundResource(R.drawable.button_white);
        btnOpt2.setBackgroundResource(R.drawable.button_white);
        btnOpt3.setBackgroundResource(R.drawable.button_white);
        btnOpt4.setBackgroundResource(R.drawable.button_white);
        btnOpt1.clearAnimation();
        btnOpt2.clearAnimation();
        btnOpt3.clearAnimation();
        btnOpt4.clearAnimation();
        nextQuizQuestion();
    }
};

private void addScore(){
    rightSound();
    correctQuestion++;
    txtTrueQuestion.setText(" "+correctQuestion +" ");
    totalScore = totalScore + 10;
    score = score + 10;
    txtScore.setText(" "+totalScore+" ");

    int rightAns = mListener.getGameData().getCountHowManyRightAnswareQuestion();
    rightAns++;
    mListener.getGameData().setCountHowManyRightAnswareQuestion(rightAns);
    mListener.getGameData().setTotalScore(totalScore);
    mListener.getGameData().saveDataLocal(settings);
    System.out.println("Right Answare: "+ mListener.getGameData().getCountHowManyRightAnswareQuestion());
}


private void wrongeQuestion(){
    playWrongSound();
    //saveScore();
    inCorrectQuestion++;
    totalScore = totalScore - 3;
    score = score - 3;
    txtFalseQuestion.setText(" "+ inCorrectQuestion +" ");

    if(btnOpt1.getText().toString().equalsIgnoreCase(level.getQuestion().get(quextionIndex).getTrueAns())){
        btnOpt1.setBackgroundResource(R.drawable.button_green);
        btnOpt1.setTextColor(getResources().getColor(R.color.White));
        btnOpt1.startAnimation(animation);
    }
    if(btnOpt2.getText().toString().equalsIgnoreCase(level.getQuestion().get(quextionIndex).getTrueAns())){
        btnOpt2.setBackgroundResource(R.drawable.button_green);
        btnOpt2.setTextColor(getResources().getColor(R.color.White));
        btnOpt2.startAnimation(animation);
    }
    if(btnOpt3.getText().toString().equalsIgnoreCase(level.getQuestion().get(quextionIndex).getTrueAns())){
        btnOpt3.setBackgroundResource(R.drawable.button_green);
        btnOpt3.setTextColor(getResources().getColor(R.color.White));
        btnOpt3.startAnimation(animation);
    }
    if(btnOpt4.getText().toString().equalsIgnoreCase(level.getQuestion().get(quextionIndex).getTrueAns())){
        btnOpt4.setBackgroundResource(R.drawable.button_green);
        btnOpt4.setTextColor(getResources().getColor(R.color.White));
        btnOpt4.startAnimation(animation);
    }

    if(totalScore<0){
        totalScore=0;
    }
}

private void saveScore(){
    editor = settings.edit();
    mListener.getGameData().setTotalScore(totalScore);
    //editor.putInt(MenuHomeScreenActivity.TOTAL_SCORE, totalScore);
    editor.putInt(MenuHomeScreenActivity.LAST_LEVEL_SCORE, score);

    if(correctQuestion>=7){
        //unlockLevelCompletedAchivement(levelNo);
        levelNo++;
        editor.putBoolean(MenuHomeScreenActivity.IS_LAST_LEVEL_COMPLETED, true);
        mListener.getGameData().setLevelCompleted(levelNo);
    }else{
        editor.putBoolean(MenuHomeScreenActivity.IS_LAST_LEVEL_COMPLETED, false);
    }
    mListener.getGameData().saveDataLocal(settings);
    editor.commit();

}

public void rightSound()
{
    if(isSoundEffect){
        AudioManager meng = (AudioManager) getActivity().getSystemService(Context.AUDIO_SERVICE);
        int volume = meng.getStreamVolume( AudioManager.STREAM_NOTIFICATION);

        if (volume != 0)
        {
            if (rightAnsware == null)
                rightAnsware = MediaPlayer.create(getActivity(), R.raw.right_ans);
            if (rightAnsware != null)
                rightAnsware.start();
        }
    }
}

private void playWrongSound(){
    if(isSoundEffect){
        AudioManager meng = (AudioManager) getActivity().getSystemService(Context.AUDIO_SERVICE);
        int volume = meng.getStreamVolume( AudioManager.STREAM_NOTIFICATION);

        if (volume != 0)
        {
            if (wrongeAnsware == null)
                wrongeAnsware = MediaPlayer.create(getActivity(), R.raw.wronge_ans);
            if (wrongeAnsware != null)
                wrongeAnsware.start();
        }
    }
    if(isVibration){
        Vibrator myVib = (Vibrator) getActivity().getSystemService(getActivity().VIBRATOR_SERVICE);
        myVib.vibrate(200);
    }

}

private void resetAllValue(){

    isSoundOn = settings.getBoolean("silentMode", true);
    levelNo = mListener.getGameData().getLevelCompleted();
    scrollView = (ScrollView)v.findViewById(R.id.scrollView);
    txtQuestionIndex = (TextView)v.findViewById(R.id.txt_question);

    txtLevel = (TextView)v.findViewById(R.id.txtLevel);
    txtLevel.setText(getString(R.string.level)+": "+levelNo);

    btnOpt1 = (Button)v.findViewById(R.id.btnOpt1);
    btnOpt2 = (Button)v.findViewById(R.id.btnOpt2);
    btnOpt3 = (Button)v.findViewById(R.id.btnOpt3);
    btnOpt3.setOnClickListener(this);
    btnOpt4 = (Button)v.findViewById(R.id.btnOpt4);
    btnOpt4.setOnClickListener(this);

    btnOpt1.setBackgroundResource(R.drawable.button_white);
    btnOpt2.setBackgroundResource(R.drawable.button_white);
    btnOpt3.setBackgroundResource(R.drawable.button_white);
    btnOpt4.setBackgroundResource(R.drawable.button_white);

    txtTrueQuestion = (TextView)v.findViewById(R.id.txtTrueQuestion);
    txtTrueQuestion.setText("0");
    txtFalseQuestion = (TextView)v.findViewById(R.id.txtFalseQuestion);
    txtFalseQuestion.setText("0");

    txtQuestion  = (TextView)v.findViewById(R.id.txtQuestion);
    imgQuestion = (ImageView)v.findViewById(R.id.imgQuestion);

    animation = new AlphaAnimation(1, 0); // Change alpha from fully visible to invisible
    animation.setDuration(500); // duration - half a second
    animation.setInterpolator(new LinearInterpolator()); // do not alter animation rate
    animation.setRepeatCount(Animation.INFINITE); // Repeat animation infinitely
    animation.setRepeatMode(Animation.REVERSE); // Reverse animation at the end so the button will fade back in
    animationFromRight = new TranslateAnimation(500f, 0f, 0f, 0f);
    animationFromRight.setDuration(600);
    animationFromLeft = new TranslateAnimation(-500f, 0f, 0f, 0f);
    animationFromLeft.setDuration(600);

    animationFromRight = new TranslateAnimation(500f, 0f, 0f, 0f);
    animationFromRight.setDuration(600);
    animationFromLeft = new TranslateAnimation(-500f, 0f, 0f, 0f);
    animationFromLeft.setDuration(600);



    isSoundEffect = settings.getBoolean(MenuHomeScreenActivity.SOUND_EFFECT, true);
    isVibration = settings.getBoolean(MenuHomeScreenActivity.VIBRATION, true);

    totalScore  = mListener.getGameData().getTotalScore();
    txtScore = (TextView)v.findViewById(R.id.txtScore);

    txtScore.setText(""+totalScore);

    Resources ress = getResources();
    progress = new ProgressDialog(getActivity());
    progress.setTitle("Подождите");
    progress.setMessage("Загрузка данных");
    progress.setCancelable(false);
    progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
    progress.show();
    LoadQuestions task = new LoadQuestions();
    task.execute(new String[] { ress.getString(R.string.question_bank_url)+levelNo });

}
public void blankAllValue() {
    quextionIndex = 0;
    isSoundEffect = false;
    isVibration = false;

    totalScore = 0;
    score = 0;
    correctQuestion = 0;
    inCorrectQuestion = 0;
}
private class LoadQuestions extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... urls) {
        questionJson="";
        for (String url : urls) {
            DefaultHttpClient client = new DefaultHttpClient();
            HttpGet httpGet = new HttpGet(url);
            try {
                HttpResponse execute = client.execute(httpGet);
                InputStream content = execute.getEntity().getContent();

                BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
                String s = "";
                while ((s = buffer.readLine()) != null) {
                    questionJson += s;
                }

            } catch (Exception e) {
                e.printStackTrace();
            }

            try {
                playQuizquestions = new ArrayList<PlayQuizQuestion>();
                JSONArray users = new JSONArray(questionJson);
                for (int i = 0; i < users.length(); i++) {
                    JSONObject c = users.getJSONObject(i);
                    PlayQuizQuestion tempQuestion = new PlayQuizQuestion(c.getString("question"));
                    tempQuestion.addOption(c.getString("optiona"));
                    tempQuestion.addOption(c.getString("optionb"));
                    tempQuestion.addOption(c.getString("optionc"));
                    tempQuestion.addOption(c.getString("optiond"));
                    String temImgName = c.getString("qimage").replace(" ", "%20");//%20
                    String imageName = ""+getResources().getString(R.string.question_image_path)+"/"+temImgName;
                    tempQuestion.setImagePath(imageName);
                    String rightAns = c.getString("rightans");

                    if(rightAns.equalsIgnoreCase("A")){
                        tempQuestion.setTrueAns(c.getString("optiona"));
                    }else if(rightAns.equalsIgnoreCase("B")){
                        tempQuestion.setTrueAns(c.getString("optionb"));
                    }else if(rightAns.equalsIgnoreCase("C")){
                        tempQuestion.setTrueAns(c.getString("optionc"));
                    }else{
                        tempQuestion.setTrueAns(c.getString("optiond"));
                    }
                    try {
                        tempQuestion.setQuestionBitmap(BitmapFactory.decodeStream((InputStream)new URL(imageName).getContent()));
                    } catch (MalformedURLException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    System.out.println(tempQuestion);
                    playQuizquestions.add(tempQuestion);

                }
                level = new PlayQuizLevel(levelNo,NO_OF_QUESTION,getActivity());
                Collections.shuffle(playQuizquestions);
                level.setQuestion(playQuizquestions);

            } catch (JSONException e) {
                Log.e("JSON Parser", "Error parsing data" + e.toString());
                e.printStackTrace();
            }
        }

        return questionJson;
    }

    @Override
    protected void onPostExecute(String result) {

        progress.cancel();
        nextQuizQuestion();
    }



    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        super.onPreExecute();

    }

}

}

1 个答案:

答案 0 :(得分:1)

检查选项是否为空并基于它隐藏/显示。

if(options.get(i).trim().isEmpty()){
   btnOpt{i}.setVisibility(View.GONE);
}
else
 {
   btnOpt{i}.setVisibility(View.VISIBLE);
 }