Android делает определенный текст жирным в textView - PullRequest
0 голосов
/ 14 марта 2019

В настоящее время я делаю последние штрихи к приложению, которое я делаю, это в основном приложение MadLibsStory. Для тех, кто не знает, что это такое ... Я, по сути, прошу пользователя ввести несколько слов, чтобы заполнить историю, которую они еще не видели. Им просто предлагают ввести тип слова (прилагательное, существительное, множественное число и т. Д.), А затем, когда все заполнители заполнены, история показывается пользователю с введенными ими словами, помещенными туда, где были заполнители. сформировать дурацкую историю.

У меня 3 занятия:

1) Экран приветствия с кнопкой. пользователь нажимает кнопку, чтобы начать вводить слова.

2) Экран ввода слова, в котором пользователь может вводить слова, пока метод getRemainingPlaceholders () не вернет 0

3) Получает завершенный объект MadLib из Activity и отображает его в TextView для пользователя со всеми введенными им словами, заполненными там, где были заполнители.

Я хотел бы найти способ сделать слова, введенные в действии 2, полужирным, когда они отображаются в задании 3 (только слова, введенные в качестве заполнителей в задании 2, а не остальная часть истории). Таким образом, пользователь может легко увидеть, какие слова принадлежат ему, потому что они будут выделены жирным шрифтом!

Все уже работает, кроме этого. Вот мой код:

MainActivity

package com.example.assignment2;

import android.content.Intent;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import java.io.IOException;
import java.io.InputStream;

/**
 * This is the main activity for the application and will display the welcome screen.
 */
public class MainActivity extends AppCompatActivity {

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

}

public void onClick(View view){
    Intent i = new Intent(this, MadLibEntry.class);
    startActivity(i);

    }
}

MadLibEntry.java

public class MadLibEntry extends AppCompatActivity {

//empty madlib object
MadLibStory mlStory = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_mad_lib_entry);
    //gets intent from main activity
    getIntent();

    Resources resources = getResources();

    String fileName = resources.getString(R.string.university);

    AssetManager assetManager = getAssets();

    try {
        //populates madlib object with given file text
        InputStream inputStream = assetManager.open(fileName);
        mlStory = new MadLibStory(inputStream);

    }catch(IOException ioe){

    }

    //text view to display first word type (adjective, noun, etc.)
    TextView wordTypeView = (TextView) findViewById(R.id.wordType);
    wordTypeView.setText(mlStory.getNextPlaceholder());
}

//when the submit button is clicked
public void onSubmit(View view){
        //text view to display word type (adjective, noun, etc.)
        TextView wordTypeView = (TextView) findViewById(R.id.wordType);
        //editText reference
        EditText wordEntryView = (EditText) findViewById(R.id.wordEntry);
        //sets the edittext view as the input the user gave
        wordEntryView.getText();
        mlStory.fillInPlaceholder(wordEntryView.getText().toString());
        //sets the word type for the user (adjective, noun, etc.)
         wordTypeView.setText(mlStory.getNextPlaceholder());
        //Starts the next activity if all of the placeholders have been filled
       if(mlStory.getPlaceholderRemainingCount() == 0) {
           //sending intent to next activity
           Intent ii = new Intent(this, MadLibResult.class);
           ii.putExtra("mlStory", mlStory);
           startActivity(ii);
           }

    }


}

MadLibResult.java

public class MadLibResult extends AppCompatActivity{

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

    //getting intent sent from activity 2
    Intent i = getIntent();
    //creating a new MadLib object and populating it with the text recieved from activity 2
    MadLibStory finalStory = (MadLibStory) i.getSerializableExtra("mlStory");
    //Textview Reference for story display
    TextView resultView = (TextView)findViewById(R.id.resultView);
    //display story to user using textview
    resultView.setText(finalStory.toString());

}

public void onClick(View view){
    Intent i = new Intent(this, MainActivity.class);
    startActivity(i);
    }
}

MadLibStory.java

public class MadLibStory extends AppCompatActivity implements Serializable {

private String text;                 // text of the Mad Lib
private List<String> placeholders;   // list of placeholders to fill in
private int filledIn;                // number of placeholders that have been filled in
private boolean htmlMode;            // set to true to surround placeholders with <b></b> tags



/** constructs a new empty MadLibStory **/
public MadLibStory() {

    init();
}

/** constructs a new MadLibStory reading its text from the
 given input stream **/
public MadLibStory(InputStream stream) {
    init();
    read(stream);
}

/** constructs a new MadLibStory reading its text from the
 given Scanner **/
public MadLibStory(Scanner input) {
    init();
    read(input);
}

/** initializes the attributes for the class **/
private void init(){
    text = "";
    placeholders = new ArrayList<String>();
    filledIn = 0;
    htmlMode = false;

}


/** resets the MadLibStory back to an empty initial state **/
public void clear() {
    text = "";
    placeholders.clear();
    filledIn = 0;
}

/** replaces the next unfilled placeholder with the given word **/
public void fillInPlaceholder(String word) {
    if (!isFilledIn()) {
        text = text.replace("<" + filledIn + ">", word);
        filledIn++;
    }
}

/** returns the next placeholder such as "adjective",
 *  or empty string if MadLibStory is completely filled in already **/
public String getNextPlaceholder() {
    if (isFilledIn()) {
        return "";
    } else {
        return placeholders.get(filledIn);
    }
}

/** returns total number of placeholders in the MadLibStory **/
public int getPlaceholderCount() {
    return placeholders.size();
}

/** returns how many placeholders still need to be filled in **/
public int getPlaceholderRemainingCount() {
    return placeholders.size() - filledIn;
}

/** returns true if all placeholders have been filled in **/
public boolean isFilledIn() {
    return filledIn >= placeholders.size();
}

/** reads initial Mad Lib Story text from the given input stream **/
public void read(InputStream stream) {
    read(new Scanner(stream));
}

/** reads initial Mad Lib Story text from the given Scanner **/
public void read(Scanner input) {
    while (input.hasNext()) {
        String word = input.next();
        if (word.startsWith("<") && word.endsWith(">")) {
            // a placeholder; replace with e.g. "<0>" so I can find/replace it easily later
            // (make them bold so that they stand out!)
            if (htmlMode) {
                text += " <b><" + placeholders.size() + "></b>";
            } else {
                text += " <" + placeholders.size() + ">";
            }
            // "<plural-noun>" becomes "plural noun"
            String placeholder = word.substring(1, word.length() - 1).replace("-", " ");
            placeholders.add(placeholder);
        } else {
            // a regular word; just concatenate
            if (!text.isEmpty()) {
                text += " ";
            }
            text += word;
        }
    }
}

/** returns MadLibStory text **/
public String toString()
{
    return text;
}
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...