Android 如何在不使用任何外部库的情况下同时使用导航抽屉和Tabhost
我想在不使用任何外部库的情况下同时使用navigation drawer和Tabhost,这可能吗 我尝试过使用Sherlock Fragment的外部库,但是,我在其他方面遇到了问题 FragmentTab1.javaAndroid 如何在不使用任何外部库的情况下同时使用导航抽屉和Tabhost,android,android-tabhost,navigation-drawer,Android,Android Tabhost,Navigation Drawer,我想在不使用任何外部库的情况下同时使用navigation drawer和Tabhost,这可能吗 我尝试过使用Sherlock Fragment的外部库,但是,我在其他方面遇到了问题 FragmentTab1.java public class FragmentTab1 extends SherlockFragment { Button postAd, browse; EditText discription; EditText price; String discriptionText;
public class FragmentTab1 extends SherlockFragment {
Button postAd, browse;
EditText discription;
EditText price;
String discriptionText;
String priceText;
String adTypetext;
RadioGroup adType;
RadioButton buy;
RadioButton sell;
Bitmap bitmap;
ProgressDialog dialog;
String encodedImage;
String userid;
TextView msgLength;
JSONArray AdsArray = null;
String TAG_ID = "id";
String TAG_IMAGE = "image";
String TAG_TYPE = "adType";
String TAG_DISCRIPTION = "description";
String TAG_PRICE = "price";
ListView lv;
ArrayList<HashMap<String, String>> adList;
private static final int PICK_IMAGE = 1;
@SuppressLint("NewApi")
@TargetApi(Build.VERSION_CODES.GINGERBREAD)
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragmenttab1, container, false);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
}
postAd = (Button) getView().findViewById(R.id.bpostAd);
discription = (EditText)getView().findViewById(R.id.etDiscription);
price = (EditText)getView().findViewById(R.id.etPrice);
final RadioGroup adType = (RadioGroup)getView().findViewById(R.id.radioGroup);
RadioButton buy = (RadioButton)getView().findViewById(R.id.rbBuy);
RadioButton sell = (RadioButton)getView().findViewById(R.id.rbSell);
browse = (Button)getView().findViewById(R.id.bBrowse);
msgLength = (TextView)getView().findViewById(R.id.tvLength);
lv = (ListView)getView().findViewById(R.id.listView1);
SharedPreferences mPrefs = getActivity().getSharedPreferences("IDvalue", 0);
userid = mPrefs.getString("userIdKey", null);
adList = new ArrayList<HashMap<String, String>>();
new LoadMyAds().execute();
TextWatcher txwatcher = new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// TODO Auto-generated method stub
int length = s.length();
int remaining = 140 - length;
msgLength.setText(String.valueOf(remaining));
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
@Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
};
discription.addTextChangedListener(txwatcher);
postAd.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
discriptionText = discription.getText().toString();
priceText = price.getText().toString();
int selectedRbId = adType.getCheckedRadioButtonId();
if (selectedRbId == R.id.rbBuy) {
adTypetext = "Buying";
}
if (selectedRbId == R.id.rbSell) {
adTypetext = "Selling";
}
if (bitmap == null) {
Toast.makeText(getActivity().getApplicationContext(),
"Please select image", Toast.LENGTH_SHORT).show();
} else {
new ImageUploadTask().execute();
UserFunctions userFunction = new UserFunctions();
JSONObject json = userFunction.postAd(encodedImage,
discriptionText, adTypetext, priceText, userid);
try {
if (json.getString("status") != null) {
String res = json.getString("status");
if (Integer.parseInt(res) == 1) {
Toast.makeText(getActivity().getApplicationContext(),
"Ad has been posted", Toast.LENGTH_LONG)
.show();
} else {
Toast.makeText(getActivity().getApplicationContext(),
"posting error", Toast.LENGTH_LONG)
.show();
}
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
});
browse.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(
Intent.createChooser(intent, "Select Picture"),
PICK_IMAGE);
} catch (Exception e) {
Toast.makeText(getActivity().getApplicationContext(), "error",
Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(), e.getMessage(), e);
}
}
});
return rootView;
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
switch (requestCode) {
case PICK_IMAGE:
if (resultCode == Activity.RESULT_OK) {
Uri selectedImageUri = data.getData();
String filePath = null;
try {
// OI FILE Manager
String filemanagerstring = selectedImageUri.getPath();
// MEDIA GALLERY
String selectedImagePath = getPath(selectedImageUri);
if (selectedImagePath != null) {
filePath = selectedImagePath;
} else if (filemanagerstring != null) {
filePath = filemanagerstring;
} else {
Toast.makeText(getActivity().getApplicationContext(), "Unknown path",
Toast.LENGTH_LONG).show();
Log.e("Bitmap", "Unknown path");
}
if (filePath != null) {
decodeFile(filePath);
} else {
bitmap = null;
}
} catch (Exception e) {
Toast.makeText(getActivity().getApplicationContext(), "Internal error",
Toast.LENGTH_LONG).show();
Log.e(e.getClass().getName(), e.getMessage(), e);
}
}
break;
default:
}
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
@SuppressWarnings("deprecation")
Cursor cursor = getActivity().managedQuery(uri, projection, null, null, null);
if (cursor != null) {
// HERE YOU WILL GET A NULLPOINTER IF CURSOR IS NULL
// THIS CAN BE, IF YOU USED OI FILE MANAGER FOR PICKING THE MEDIA
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} else
return null;
}
public void decodeFile(String filePath) {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, o);
// The new size we want to scale to
final int REQUIRED_SIZE = 1024;
// Find the correct scale value. It should be the power of 2.
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
bitmap = BitmapFactory.decodeFile(filePath, o2);
Log.e("Decodefile", "bitmap set");
// imgView.setImageBitmap(bitmap);
}
class ImageUploadTask extends AsyncTask<Void, Void, String> {
@Override
protected String doInBackground(Void... params) {
// TODO Auto-generated method stub
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 100, bos);
byte[] data = bos.toByteArray();
// encodedImage = new String(data);
encodedImage = Base64.encodeToString(data, Base64.DEFAULT);
return encodedImage;
}
}
class LoadMyAds extends AsyncTask<Void, Void, String> {
@Override
protected String doInBackground(Void... params) {
// TODO Auto-generated method stub
UserFunctions userFunction = new UserFunctions();
String type = "MyAds";
JSONObject json = userFunction.myAds(userid, type);
try {
if (json.getString("status") != null) {
String res = json.getString("status");
if (Integer.parseInt(res) == 1) {
AdsArray = json.getJSONArray("adsArray");
for (int i = 0; i < AdsArray.length(); i++) {
JSONObject c = AdsArray.getJSONObject(i);
String id = c.getString(TAG_ID);
String adType = c.getString(TAG_TYPE);
String description = c.getString(TAG_DISCRIPTION);
String price = c.getString(TAG_PRICE);
String image = c.getString(TAG_IMAGE);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_ID, id);
map.put(TAG_IMAGE, image);
map.put(TAG_TYPE, adType);
map.put(TAG_DISCRIPTION, description);
map.put(TAG_PRICE, price);
adList.add(map);
}
} else {
Toast.makeText(getActivity().getApplicationContext(),
"parsing error", Toast.LENGTH_LONG).show();
}
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
//image parameter need to be added
ListAdapter adapter = new SimpleAdapter(getActivity(), adList, R.layout.ad_list_item , new String[] { TAG_DISCRIPTION, TAG_PRICE} , new int[] { R.id.title, R.id.price});
lv.setAdapter(adapter);
}
}
}
由于在创建片段的实际视图之前调用了
getView()
,因此得到了一个很大的NullPointerException
。因此,在onCreateView()
中,您无法通过id找到视图
此问题的解决方案是尝试使用rootview.findViewById()
而不是getView().findViewById()
另外,您是否注意到,您已将rootview充气,但未对其进行任何处理,然后将其返回。因此,只需使用它来查找视图,并将所有侦听器绑定到按钮等等
至于映像的问题,这是由您自己在onActivityResult()方法中的实现引起的。我不知道你的应用程序是如何工作的,所以我将在这里发布我的代码来实现类似的东西
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
Uri uri = data.getData();
ContentResolver cr = this.getContentResolver();
try {
Bitmap bitmap = BitmapFactory.decodeStream(cr.openInputStream(uri));
imageView = (ImageView) findViewById(R.id.image);
imageView.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
Log.e("Exception", e.getMessage(), e);
}
}
super.onActivityResult(requestCode, resultCode, data);
}
我认为应该很好。你应该说明你遇到了哪些错误。你试图实现什么?我已经展示了我的代码。谢谢你的回复@chintankhetiyaTry在
onCreateView()
方法中用rootView替换getView()
,非常感谢,现在我能够看到xml文件,我是说它被重定向了,现在我在这里面临另一个问题。在上面的代码中,我正在尝试选择一个图像,除了从手机中选择一个图像外,其他一切都很完美。如果你能帮我做同样的事情。提前谢谢@Izzyleung你能帮我做同样的事情吗?我在这里还面临一个问题,我在上面的评论中提到了这个问题@Izzyleuntanks很多,现在我能够看到xml文件,我是说它被重定向了,现在我在这里面临另一个问题。在上面的代码中,我正在尝试选择一个图像,除了从手机中选择一个图像外,其他一切都很完美。如果你能帮我做同样的事情。提前感谢@LZZYLEUNGOPS,这可能是由您自己在onActivityResult()方法中的实现引起的。我记得我编写了一个类似的应用程序,从galary中选取一幅图像,他们将其设置为ImageView,我在上面的回答中加入了代码,请检查一下@如果代码已经发布,希望能有所帮助。只是打了个盹,然后就睡着了-(抱歉让您久等了。@IzzyLeaung我已经用Activity而不是Fragment实现了上面的代码,拾取图像的功能运行得很好。但是当我使用Fragment时,OnActivityResult方法还没有调用。我搜索了类似的问题,发现很多人都遇到了这个问题,但我仍然无法解决这个问题:/
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
Uri uri = data.getData();
ContentResolver cr = this.getContentResolver();
try {
Bitmap bitmap = BitmapFactory.decodeStream(cr.openInputStream(uri));
imageView = (ImageView) findViewById(R.id.image);
imageView.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
Log.e("Exception", e.getMessage(), e);
}
}
super.onActivityResult(requestCode, resultCode, data);
}