我想在textview之前添加图片,并希望在每一行中自定义TextView,但是我很难实现它,因为已经内置了xml这样的布局文件
simple_list_item_1 。请帮助我如何实施它。
这是simple_list_item编码
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2006 The Android Open Source Project
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/text1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="20sp"
android:textStyle="bold"
android:textAppearance="?android:attr/textAppearanceListItemSmall"
android:gravity="center_vertical"
android:paddingStart="?android:attr/listPreferredItemPaddingStart"
android:paddingEnd="?android:attr/listPreferredItemPaddingEnd"
android:minHeight="?android:attr/listPreferredItemHeightSmall"
/>
主要活动
public class MainActivity extends ListActivity {
private ListActivity activity;
final static String ScreenName = "google";
final static String LOG_TAG = "rnc";
ListView listview;
TextView text;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.twit_list);
listview = this.getListView();
activity = this;
downloadTweets();
listview.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// selected item
String lst_txt = parent.getItemAtPosition(position).toString().trim();
// Launching new Activity on selecting single List Item
Intent i = new Intent(MainActivity.this, SingleListItem.class);
// sending data to new activity
i.putExtra("product",lst_txt );
startActivity(i);
}
});
}
// download twitter timeline after first checking to see if there is a network connection
public void downloadTweets() {
ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
new DownloadTwitterTask().execute(ScreenName);
} else {
Log.v(LOG_TAG, "No network connection available.");
}
}
// Uses an AsyncTask to download a Twitter user's timeline
private class DownloadTwitterTask extends AsyncTask<String, Void, String> {
final static String CONSUMER_KEY = "keyvaluexxxxx";
final static String CONSUMER_SECRET = "secretkeyxxxxxxx";
final static String TwitterTokenURL = "https://api.twitter.com/oauth2/token";
final static String TwitterStreamURL = "https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=";
private ProgressDialog progressDialog;
@Override
// can use UI thread here
protected void onPreExecute() {
//this.progressDialog = ProgressDialog.show(Boys.this, ""," Look whose back !! Ok Let me see what i have for you ");
try{
progressDialog = new ProgressDialog(MainActivity.this,AlertDialog.THEME_HOLO_DARK);
progressDialog.setIndeterminate(true);
progressDialog.setIndeterminateDrawable(getResources().getDrawable(R.drawable.loader_2));
progressDialog.setMessage("Please Wait ! Unwrapping Something for You...");
progressDialog.show();
progressDialog.setCancelable(false);
progressDialog.setCanceledOnTouchOutside(false);
}
catch(Exception e)
{
this.progressDialog.dismiss();
Toast.makeText(getApplicationContext(),e.toString(), Toast.LENGTH_LONG).show();
}
}
@Override
protected String doInBackground(String... screenNames) {
String result = null;
if (screenNames.length > 0) {
result = getTwitterStream(screenNames[0]);
}
return result;
}
// onPostExecute convert the JSON results into a Twitter object (which is an Array list of tweets
@Override
protected void onPostExecute(String result) {
Twitter twits = jsonToTwitter(result);
// lets write the results to the console as well
for (Tweet tweet : twits) {
Log.i(LOG_TAG, tweet.getText());
}
// send the tweets to the adapter for rendering
ArrayAdapter<Tweet> adapter = new ArrayAdapter<Tweet>(activity, android.R.layout.simple_list_item_1, twits);
setListAdapter(adapter);
this.progressDialog.dismiss();
}
// converts a string of JSON data into a Twitter object
private Twitter jsonToTwitter(String result) {
Twitter twits = null;
if (result != null && result.length() > 0) {
try {
Gson gson = new Gson();
twits = gson.fromJson(result, Twitter.class);
} catch (IllegalStateException ex) {
// just eat the exception
}
}
return twits;
}
// convert a JSON authentication object into an Authenticated object
private Authenticated jsonToAuthenticated(String rawAuthorization) {
Authenticated auth = null;
if (rawAuthorization != null && rawAuthorization.length() > 0) {
try {
Gson gson = new Gson();
auth = gson.fromJson(rawAuthorization, Authenticated.class);
} catch (IllegalStateException ex) {
// just eat the exception
}
}
return auth;
}
private String getResponseBody(HttpRequestBase request) {
StringBuilder sb = new StringBuilder();
try {
DefaultHttpClient httpClient = new DefaultHttpClient(new BasicHttpParams());
HttpResponse response = httpClient.execute(request);
int statusCode = response.getStatusLine().getStatusCode();
String reason = response.getStatusLine().getReasonPhrase();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent();
BufferedReader bReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
String line = null;
while ((line = bReader.readLine()) != null) {
sb.append(line);
}
} else {
sb.append(reason);
}
} catch (UnsupportedEncodingException ex) {
} catch (ClientProtocolException ex1) {
} catch (IOException ex2) {
}
return sb.toString();
}
private String getTwitterStream(String screenName) {
String results = null;
// Step 1: Encode consumer key and secret
try {
// URL encode the consumer key and secret
String urlApiKey = URLEncoder.encode(CONSUMER_KEY, "UTF-8");
String urlApiSecret = URLEncoder.encode(CONSUMER_SECRET, "UTF-8");
// Concatenate the encoded consumer key, a colon character, and the
// encoded consumer secret
String combined = urlApiKey + ":" + urlApiSecret;
// Base64 encode the string
String base64Encoded = Base64.encodeToString(combined.getBytes(), Base64.NO_WRAP);
// Step 2: Obtain a bearer token
HttpPost httpPost = new HttpPost(TwitterTokenURL);
httpPost.setHeader("Authorization", "Basic " + base64Encoded);
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
httpPost.setEntity(new StringEntity("grant_type=client_credentials"));
String rawAuthorization = getResponseBody(httpPost);
Authenticated auth = jsonToAuthenticated(rawAuthorization);
// Applications should verify that the value associated with the
// token_type key of the returned object is bearer
if (auth != null && auth.token_type.equals("bearer")) {
// Step 3: Authenticate API requests with bearer token
HttpGet httpGet = new HttpGet(TwitterStreamURL + screenName);
// construct a normal HTTPS request and include an Authorization
// header with the value of Bearer <>
httpGet.setHeader("Authorization", "Bearer " + auth.access_token);
httpGet.setHeader("Content-Type", "application/json");
// update the results with the body of the response
results = getResponseBody(httpGet);
}
} catch (UnsupportedEncodingException ex) {
} catch (IllegalStateException ex1) {
}
return results;
}
}
}
这里是 twit_list.xml 附带 MainActivity.java
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/bis"
>
<ListView
android:id="@android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</ListView>
</LinearLayout>
创建一个custom_item
内部布局文件夹
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<ImageView
android:id="@+id/listItemImgView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="@string/done"
android:src="@drawable/ic_launcher" />
<TextView
android:id="@+id/listItemTxtView"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1" />
</LinearLayout>
创建一个这样的自定义适配器
public class CustomAdapter extends ArrayAdapter<Tweet> {
private Context mContext;
private int layoutId;
private ArrayList<Tweet> dataList;
public CustomAdapter(Context context, int resourceId,
ArrayList<Tweet> objects) {
super(context, resourceId, objects);
// TODO Auto-generated constructor stub
mContext = context;
layoutId = resourceId;
dataList = objects;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder viewHolder;
if(convertView == null) {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(layoutId, null);
viewHolder = new ViewHolder();
viewHolder.listItemTxtView = (TextView) convertView.findViewById(R.id.listItemTxtView);
viewHolder.listItemImgView = (ImageView) convertView.findViewById(R.id.listItemImgView);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.listItemTxtView.setText(dataList.get(position).toString());
//place picasso jar into libs folder of your project and use it for download and set images like this
Picasso.with(context).load("url of image you want to load").into(viewHolder.listItemImgView);
return convertView;
}
private class ViewHolder {
TextView listItemTxtView;
ImageView listItemImgView;
}
}
picasso
从这里下载罐子
代替这个
ArrayAdapter<Tweet> adapter = new ArrayAdapter<Tweet>(activity, android.R.layout.simple_list_item_1, twits);
setListAdapter(adapter);
用这个
CustomAdapter adapter = new CustomAdapter(MainActivity.this, R.layout.custom_item, twits);
setListAdapter(adapter);
问题内容: 当用户访问列表中可见的项目时,如何在底部显示进度栏。 我编写了一个代码,其中使用Web服务获取数据,现在我想填充部分记录,因为我的JSON中大约有 630条记录 。 这是我用来从JSON获取数据并填充到RecyclerView中的整个代码。 这是我的JSON的外观,但是真实的JSON包含600多个记录: 有人可以指导我在我的代码中进行更改的地方吗? 每当用户使用进度条滚动到底部时,我想
问题内容: 我正在使用iOS的Google Maps API,并想使用标记聚类实用程序。我想出了如何显示聚簇标记,但是我想自定义标记。有人可以解释如何设置/更改每个标记或群集标记的图标和标题吗?示例代码将非常有帮助。 到目前为止,这就是我所拥有的。我不知道该如何处理renderClusters和更新函数。 问题答案: 在 Swift 4上 ,我找到了一种针对聚簇标记的干净解决方案,可以为聚簇使用自
问题内容: 我是SwiftUI的新手。我有三个视图,我希望它们在PageView中。我想像滑动浏览器一样滑动每个“视图”,并希望这些小点表示我所在的视图。 问题答案: 页面控制 您的页面浏览量 您的页面视图控制器 假设您有一个类似的观点 您可以像这样在主swiftUI视图中使用此组件。
问题内容: 我有指令,它是带有后退按钮的网站标题,我想单击可返回到上一页。我如何以有角度的方式做到这一点? 我努力了: 这是指令js: 但什么也没发生。我查看了有关$ location 的angular.js API,但未找到有关后退按钮或的任何信息。 问题答案: 您需要在指令中使用链接函数: 参见jsFiddle。
问题内容: 我想知道是否有人知道如何在node.js中实现setTimeout。我相信我在某处读到它不是V8的一部分。我迅速尝试找到实现,但是在source(BIG)中找不到它。例如,我找到了这个timers.js文件,然后例如链接到timer_wrap.cc。但是这些文件并不能完全回答我的所有问题。 V8有实施吗?我想从源头上也可以得出答案。 如何实施?javascript还是本机还是两者结合?
问题内容: 我以前的编程中,代码段仅用于调试目的(记录命令等)。通过使用预处理程序指令,可以完全禁用这些语句以进行生产,如下所示: 做类似的事情的最好方法是什么? 问题答案: 如果只想禁用日志记录方法,请使用该模块。如果日志级别设置为排除调试语句,那么它将非常接近无操作(它仅检查日志级别并返回而不插入日志字符串)。 如果要在特定条件下以字节码编译时实际删除代码块,则唯一的选择是相当神秘的全局变量。