我正在创建一个包含“每日提示”功能的应用。这本质上是一个弹出窗口,由按钮激活。它目前有填充文本,但我正在尝试创建一种读取文本文件(存储在 src/main/assets 中)的方法,并在弹出窗口中显示单独的行。我怎样才能做到这一点?文本文件中的这些行通过回车键进行个性化。我会找到一种方法,在每次单击按钮时显示独特的提示,但我稍后会讨论该部分。
这是弹出窗口本身的代码:
public class homeFragmentDialog extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AlertDialog.Builder builder1 = new AlertDialog.Builder(this);
builder1.setMessage("Filler text.");
builder1.setCancelable(true);
builder1.setPositiveButton(
"Close",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert11 = builder1.create();
alert11.show();
}
}
为了以防万一,这里是包含激活前一个 Activity 的按钮的 fragment 文件:
public class homeFragment extends Fragment {
View rootView;
private Button button0;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_home, container, false);
button0 = (Button) rootView.findViewById(R.id.buttonDialog);
button0.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), homeFragmentDialog.class);
startActivity(intent);
}
});
return rootView;
}
}
最佳答案
您可以使用getAssets()如果您访问上下文:
try {
InputStream inputStream = getAssets().open("textfile.txt");
builder1.setMessage(convertStreamToString(inputStream));
} catch (IOException e){
// Log exception
}
convertStreamToString() 来自哪里 Pavel Repin's answer :
static String convertStreamToString(java.io.InputStream is) {
java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
return s.hasNext() ? s.next() : "";
}
或者您可以读取所需的字节数(在您的情况下为一行)。
编辑:
您可以使用此方法来获取单行,而不是convertStreamToString():
static String getLineFromStream(java.io.InputStream is, int linePos){
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = null;
try {
for (int i = 0; i <= linePos; i++) {
line = br.readLine();
}
} catch (IOException e){
// Handle exception here (or you can throw)
}
return line;
}
关于java - Android Studio : Read in a text file, 在弹出窗口中显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36073531/